package com.xuliugen.lsm.core;

import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor.AbortPolicy;
import java.util.concurrent.TimeUnit;

import com.xuliugen.lsm.util.Task;
import com.xuliugen.lsm.util.Vector;

/**
 * 压缩
 * @param <K>
 * @param <V>
 */
public class Compaction<K extends Comparable<K>, V> {

    private ExecutorService threadPool;

    private final Map<K, Integer> deleted;

    Compaction(Map<K, Integer> deleted) {
        int coreSize = Runtime.getRuntime().availableProcessors() + 1;
        int maxSize = (coreSize - 1) >> 1;
        this.deleted = deleted;
        threadPool = new ThreadPoolExecutor(coreSize, maxSize,
                0L, TimeUnit.MINUTES,
                new LinkedBlockingQueue<>(),
                new AbortPolicy());
    }

    /**
     * 压缩具体的内容，将传入的数据压缩
     * @param ssTable
     * @return
     */
    boolean compaction(Vector<K, V> ssTable) {
        if (ssTable == null || ssTable.size() <= 0) {
            throw new RuntimeException("SSTable is empty !");
        }

        //初始化左右
        int left = 0;
        int right = ssTable.getArrayLen();

        while (left < right) {
            threadPool.submit(new Task<>(ssTable, left, right, deleted));
        }
        ssTable.setSize(left);
        return true;
    }

}
